import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
    Row, Col, Card, Form, Input, Select, Icon,
    Button, Dropdown, Menu, InputNumber,
    DatePicker, Modal, message, Badge, Table,
    Divider, Tag, Tree, Tooltip, TreeSelect
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { routerRedux } from 'dva/router';
import DescriptionList from '../../components/DescriptionList';
import styles from './OrganizationEdit.less';

/*
 组织架构添加组织界面
*/const FormItem = Form.Item;
const { Description } = DescriptionList;
const { TextArea } = Input;

const { Option, OptGroup } = Select;

@connect(({ structure }) => ({
    structure,
}))
@Form.create()
export default class OrganizationEdit extends PureComponent {
    state = {
        modalVisible: false,
        isEdit: true,
        branch: {},
        parentId: '',
        value: '',
        treeData: [],
        treeBranchData: [],
        treeSelelctValue: -1,
    };


    componentDidMount() {
        const { dispatch } = this.props;
        dispatch({
            type: 'structure/fetch',
            payload: {
                // userId: '1' 
            },
        });
    }

    onSelect = (selectedKeys, info) => {
        // console.log('selected', selectedKeys, info);
    }

    // handleAddJobs = () => {
    //     this.props.dispatch(routerRedux.push('/system/add-group'));
    // }

    handleAddJobs = () => {
        this.setState({
            modalVisible: true,
            isEdit: true,
        });
        this.props.dispatch({
            type: 'structure/getParentBranch',
            payload: {
                // branchId: record.id,
            },
            callback: () => {
                const { structure: { superiorBranchList } } = this.props;
                const superiorBranchListToDisplay = [superiorBranchList];
                superiorBranchListToDisplay.length>0 &&
                    this.wrapTreeDataRecord(superiorBranchListToDisplay);
                this.setState({
                    treeData: superiorBranchListToDisplay,
                });
            },
        })
    }

    handleModalCancel = () => {
        // this.props.form.resetFields();
        this.setState({
            modalVisible: false,
        });
    }

    deleteBranch = (id) => {
        this.props.dispatch({
            type: 'structure/deleteBranch',
            payload: {
                branchId: id
            },
            callback: () => {
                this.props.dispatch({
                    type: 'structure/fetch',
                });
            },
        })
    }

    edit = (record) => {
        this.props.dispatch({
            type: 'structure/getEditBranchList',
            payload: {
                branchId: record.id,
            },
            callback: () => {
                const { structure: { editBranchList } } = this.props;
                const superiorToDisplay = editBranchList;
                superiorToDisplay.length>0&&this.wrapTreeDataRecord(superiorToDisplay);
                this.setState({
                    treeBranchData: superiorToDisplay,
                });
            },
        })
        this.setState({
            modalVisible: true,
            isEdit: false,
            branch: record,
        })
    }

    hanleCreateUserModalOk = () => {
        const { validateFieldsAndScroll } = this.props.form;

        validateFieldsAndScroll((error, values) => {
            if (!error) {
                if (values != null) {
                    this.setState({
                        modalVisible: false,
                    });
                }
                if (this.state.isEdit) {
                    this.props.form.resetFields();
                    this.props.dispatch({
                        type: 'structure/addOrganization',
                        payload: {
                            orgName: values.orgName,
                            parentId: values.superior,
                            orgNumber: values.orgNumber,
                            remark: values.remark,
                        },
                        callback: () => {
                            this.props.dispatch({
                                type: 'structure/fetch',
                                payload: {
                                    // userId: '1' 
                                },
                            });
                        },
                    });
                } else {
                    this.props.form.resetFields();
                    this.props.dispatch({
                        type: 'structure/update',
                        payload: {
                            id: this.state.branch.id,
                            orgName: values.orgName,
                            parentId: values.superior,
                            orgNumber: values.orgNumber,
                            remark: values.remark,
                        },
                        callback: () => {
                            this.props.dispatch({
                                type: 'structure/fetch',
                                payload: {
                                    // userId: '1' 
                                },
                            });
                        },
                    });
                }
            }
        });
    };

    handleBranchChange = (value) => {
        this.setState({
            parentId: value,
        })
    }

    hanleTreeSelectChange = (value) => {
        // console.log("hanleTreeSelectChange");
        // console.log(value);
        //console.log(arguments);
        //console.log(value);
        //this.setState({ value });
    }

    columns = [{
        title: '组织名称',
        dataIndex: 'orgName',
        key: 'orgName'
    }, {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark'
    }, {
        title: '操作',
        dataIndex: 'id',
        key: 'id',
        render: (text, record) => (
            <Fragment>
                <a onClick={() => this.edit(record)}>编辑</a>
                <Divider type="vertical" />
                <a onClick={() => this.deleteBranch(record.id)}>删除</a>
            </Fragment>
        )
    },];

    wrapTreeDataRecord = (list) => {
        console.log("list",list)
        if(list.length > 0){
            list.map((item => {
                item.label = item.orgName;
                item.value = `${item.id}`;
                if (this.state.isEdit) {
                    if (item.children && item.children.length > 1) {
                        this.wrapTreeDataRecord(item.children);
                    }
                } else {
                    if (item.children) {
                        if (item.children.parentId == item.id) {
                            this.setState({
                                treeSelelctValue: item.id
                            })
                        }
                    }
                }
            }));
        }   
    }

    render() {
        const { structure: { branchList, branchLoading, loading, superiorList, superiorBranchList, editBranchList } } = this.props;

        const { modalVisible, isEdit } = this.state;
        const { getFieldDecorator } = this.props.form;

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };

        return (
            <PageHeaderLayout title="组织架构维护">
                <Card
                    bordered={false} >
                    <DescriptionList style={{ marginBottom: 32 }} col={2}>
                        <Row>
                            <div className={styles.tableListOperator}>
                                <Button style={{ marginBottom: 30 }} icon="plus" type="primary" onClick={() => this.handleAddJobs()}>
                                    添加组织
                                </Button>
                            </div>
                        </Row>
                    </DescriptionList>
                    <Table
                        bordered
                        dataSource={branchList}
                        columns={this.columns}
                        rowKey="id"
                        loading={branchLoading}
                    />
                </Card>
                <Modal
                    title={isEdit ? '添加组织' : '编辑组织信息'}
                    visible={this.state.modalVisible}
                    confirmLoading={branchLoading}
                    onOk={this.hanleCreateUserModalOk}
                    onCancel={this.handleModalCancel}
                >
                    <Form onSubmit={this.handleSubmit}>
                        <FormItem {...formItemLayout} label="组织名称">
                            {getFieldDecorator('orgName', {
                                initialValue: isEdit ? null : this.state.branch.orgName,
                                rules: [{
                                    required: true, message: '请输入组织名称',
                                }],
                            })(
                                <Input placeholder="请输入组织名称" />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="上级组织">
                            {getFieldDecorator('superior', {
                                initialValue: isEdit ? null : this.state.treeSelelctValue == -1 ? null : this.state.treeSelelctValue,
                                rules: [{
                                    required: true, message: '请选择上级组织',
                                }],
                            })(
                                <TreeSelect
                                    style={{ width: '100%' }}
                                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                    treeNodeLabelProp="orgName"
                                    treeData={isEdit ? this.state.treeData : this.state.treeBranchData}
                                    placeholder="请选择"
                                    treeDefaultExpandAll
                                    // value={this.state.treeSelelctValue}
                                    onSelect={this.hanleTreeSelectChange}
                                />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="组织编码">
                            {getFieldDecorator('orgNumber', {
                                initialValue: isEdit ? null : this.state.branch.orgNumber,
                                rules: [{
                                    required: true, message: '请输入组织编码',
                                }],
                            })(
                                <Input placeholder="请输入组织编码" />
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="备注">
                            {getFieldDecorator('remark', {
                                initialValue: isEdit ? null : this.state.branch.remark,
                                rules: [{
                                    required: true, message: '请输入备注',
                                }],
                            })(
                                <TextArea placeholder="请输入备注" rows={4} />
                            )}
                        </FormItem>
                    </Form>
                </Modal>
            </PageHeaderLayout>
        );
    }
}